<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto">
                    <el-form-item label="开始日期" size="small">
                        <el-date-picker 
                            size="small"
                            v-model="paramsForm.begindate"
                            type="date"
                            placeholder="请选择日期"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD"
                            :value-on-clear="''"
                        />
                    </el-form-item>
                    <el-form-item label="结束日期" size="small">
                        <el-date-picker 
                            size="small"
                            v-model="paramsForm.enddate"
                            type="date"
                            placeholder="请选择日期"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD"
                            :value-on-clear="''"
                        />
                    </el-form-item>
                    <el-form-item label="站点:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.stations" 
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip
                                placeholder="可留空" size="small" style="width: 150px"
                                @change="changeStations"    
                                @visible-change="getStations"                   
                            >
                            <template #header>
                                    <el-checkbox
                                        v-model="stationCheckAll"
                                        :indeterminate="stationIndeterminate"
                                        @change="stationHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in stationsArr" :label="item.DESCRIPTION" :value="item.LOCATION" :key="item.LOCATION"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="设备描述" size="small">
                        <el-input v-model="paramsForm.sbdesc" size="small"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getGccList(paramsForm)"
                        :loading = "loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control 
                :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow"
                :permObj="permObj"
                @showDownload="showDownloadBox"                               
                @downloadExcelPaging="downloadExcelPaging(newDatasArr,'devicesTable','GCC信息')"
                @downloadExcelAll="downloadExcelAll(datasArr,'GCC信息')"
                @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel',selectGccList)"
                @batchUpload="batchUpload"
            ></Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage"
                v-model:pageSize="pageSize"
                @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)"
                @toFirst="toFirstPage"
                @toEnd="toEndPage"
                @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"
            ></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%"  v-loading="loading" 
                @selection-change="handleSelectionChange"
                id="devicesTable"
            >
                <el-table-column type="selection" width="50" v-if="selectShow"/>
                <el-table-column fixed prop="ID" label="ID" width="70" />
                <el-table-column prop="EVENTTIME" label="事件时间" width="180" >
                    <template #default="{row}">
                        {{ dateFormatTimeStamp(row.EVENTTIME) }}
                    </template>
                </el-table-column>
                <el-table-column fixed prop="ALARM_REGION" label="报警分区" width="180" />
                <el-table-column prop="SBDESC" label="设备描述" width="180" />
                <el-table-column prop="STATUS" label="状态" width="120" />
                <el-table-column prop="LOCATION" label="位置" width="80" />
                <el-table-column prop="LOCDESC" label="站点" width="120" />                         
                <el-table-column fixed="right" label="Operations" min-width="60"
                    width="210"
                    v-perm="permObj.delete"
                >
                    <template #default="{row}">                           
                        <el-button  type="danger" size="small" class="del" title="删除" 
                            @click="editSubmit('delete',row)"
                        >
                            <el-icon><DeleteFilled /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>               
            </el-table>
        </template>
    </AdminSkeleton>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys" :dateType="dateType"
        @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate',uploadTable)"
        @batchAdd="editSubmit('batchAdd',uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table','GCC信息导入模板')"
    > 
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column type="selection" width="50" v-if="selectShow"/>
            <el-table-column fixed prop="ID" label="ID" width="70" />
                <el-table-column prop="EVENTTIME" label="事件时间" width="180" >
                    <template #default="{row}">
                        {{ dateFormatTimeStamp(row.EVENTTIME) }}
                    </template>
                </el-table-column>
                <el-table-column prop="ALARM_REGION" label="报警分区" width="180" />
                <el-table-column prop="SBDESC" label="设备描述" width="180" />
                <el-table-column prop="STATUS" label="状态" width="120" />
                <el-table-column prop="LOCATION" label="位置" width="80" />         
        </el-table>
    </Dialog>
</template>

<script setup>
import AdminSkeleton from '@/components/AdminSkeleton.vue';
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Dialog from '@/components/Dialog.vue'
// import Drawer from '@/components/Drawer.vue'
import {ref , reactive} from 'vue'
import {xfjcStore} from '@/stores/jcStore'
import {getStationsInfo , getGccListInfo , editManyGccListInfo , editGccListInfo} from '@/utils/xfjcApi/gccList'
import { msgOpen } from '@/utils/msg'
import { dateFormatTimeStamp } from '@/utils/dateFormat'
import { exportClickFromTableId , exportClickFromDatas } from '@/utils/downloadExcel'
import { paging } from '@/utils/paging'
import {confirm ,confirmBatch} from '@/utils/confirm'
 

//权限对象--用于控制按钮显示
const permObj = {
    add:{name:'GccList',type:'add'},
    update:{name:'GccList',type:'update'},
    delete:{name:'GccList',type:'delete'}
}

let useJcStore = xfjcStore()
const {
    datasArr, 
    datasLength,
    firstPage,
    pageSize, 
    countPage,
    newDatasArr, 
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页


//一、查询参数
//#region 
/************************************************************************************************************************************** */
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)
let loading = ref(false)

//提交的表单参数对象
let paramsForm = reactive({
    begindate:"",
    enddate:"",
    stations:[],
    sbdesc:"",
})

//获取站点信息
const getStations = async ()=>{
    if(!useJcStore.gccStations.length){
        let stations = await getStationsInfo()
        // console.log(stations)
        if(stations.status){
            stationsArr.value = stations.resDatas.stations
            useJcStore.setGccStations(stations.resDatas.stations) 
        }
    }else{
        stationsArr.value = useJcStore.gccStations
    }
}

/**
 * 站点变更
 * @param val 选中的站点值
 */
 const changeStations = (val) => {
    // console.log(val)
    // console.log(stationsArr.value.length)
    if(Array.isArray(val)){
        if(val.length === 1){
            //取消全选
            if(stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            } 
        }
        else if(val.length === 0){
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if(val.length > 1){
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if(val.length === stationsArr.value.length){
                stationCheckAll.value = true
                stationIndeterminate.value = false  
            } else{
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
 * 站点全选
 * @param val 站点全选值
 */
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

/**
 * 查询
 * @param form 表单参数
 */
const getGccList = async (form)=>{    
    // console.log(form)          
    if(form.begindate === '' || form.enddate === '') msgOpen('开始日期和结束日期不能为空')
    if(form.begindate && form.enddate) {
        if(form.begindate > form.enddate){
            msgOpen('开始日期不能大于结束日期')
        }else{
            loading.value = true
            let res = await getGccListInfo(form)
            // console.log(res)
            pagingPreprocessing(res.resDatas.gccList) //分页前置处理
            loading.value = false
        }
    }  
        
}
/******************************************************************************************************************** */
//#endregion

//二、批量处理
//#region 
/******************************************************************************************************************** */
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectGccList = ref([]) //选中的设备行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "ID",
    "EVENTTIME",
    "ALARM_REGION",
    "SBDESC",
    "STATUS",
    "LOCATION",
]) //上传的字段
let dateType = ref('datetime') //上传日期类型，date：日期，datetime：日期时间


const batchEdit = ()=>{   
    if(newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
 const handleSelectionChange = (val)=>{
    selectGccList.value = val 
}

//批量上传
let uploadTable = ref([])
const batchUpload = ()=>{
    // console.log('batchUpload');
    dialogRef.value.open()       
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e)=>{    
    // console.log(e.value)           
    uploadTable = e.value   
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = ()=>{
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data,tableId,fileName)=>{
    data.length ? exportClickFromTableId(tableId,fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data,fileName)=>{   
    data?.forEach(item => item.EVENTTIME = dateFormatTimeStamp(item.EVENTTIME))
    if(data.length){
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝        
        exportClickFromDatas(newData,fileName)
    }else{
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
 const downloadTemplate = (tableId,fileName)=>{
    // console.log(tableId)
    exportClickFromTableId(tableId,fileName)
}

/******************************************************************************************************************** */
//#endregion

/**
 * 处理GCC信息 编辑、删除、批量操作
 * @param type 操作类型，batchDel：批量删除 、batchUpdate：批量更新、batchAdd：批量新增、delete：删除、update：更新、add：新增
 * @param data 选中的设备数据 
 */
 const editSubmit = async (type,data) => {
    // console.log(type)
    // console.log(data) 
    if(type === 'delete'){
        let res = await confirm(data.ID)
        if(res){
            let newGccList = await editGccListInfo(type,data)
            newGccList.status ? msgOpen(newGccList.msg,'success') : msgOpen(newGccList.msg)
            getGccList(paramsForm)
        }
    }
    if(type === 'batchAdd' || type === 'batchUpdate'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){
            // console.log(data[i]);            
            if(type === 'batchUpdate' && !data[i].ID){
                msgOpen("更新设备，请填写ID！")
                editBatchStatus.value = false
                break
            }else if(type === 'batchAdd' && data[i].ID){
                msgOpen("新增设备，ID请留空！")
                editBatchStatus.value = false
                break  
            }else{
                let row
                if(type === 'batchAdd'){
                    row = Object.values(data[i]) //将对象值转成数组
                }else{
                    row = data[i] //传给后端(ORACLE也可接收数组对象，处理时SQL绑定变量须于数组对象内的KEY值一致)
                    // console.log(data[i]);                   
                }                               
                // console.log(row);
                rowsArr.value.push(row)
            }
        } 
        if(editBatchStatus.value){
            let newGccList = await editManyGccListInfo(type,rowsArr.value)
            dialogRef.value.close()
            uploadTable = ref([])
            newGccList.status ? msgOpen(newGccList.msg,'success') : msgOpen(newGccList.msg)
            getGccList(paramsForm) 
        }
    } 
    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            // console.log(data)            
            let idsArrs = []
            data.forEach(item => {
                let idsArr = []
                idsArr.push(item.ID)
                idsArrs.push(idsArr)
            })
            let res = await confirmBatch(idsArrs.length)
            if(res){
                let newGccList = await editManyGccListInfo(type,idsArrs)
                newGccList.status ? msgOpen(newGccList.msg,'success') : msgOpen(newGccList.msg)
                getGccList(paramsForm)
            }
        }
    }
}


</script>

<style lang="less" scoped>
.params-form{
    height: 100%;
    width: 100%;
    .el-form{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .el-form-item{
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }    
}
.el-table{
    height: 95%;
}
.batchChangeStatus{
    font-size: .625rem;
    margin-left: .625rem;
}

.submit-btn{
    margin-left:.625rem;
}
</style>